package com.taoym.voucher.job.job;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoym.voucher.common.enums.ActInfoEnum;
import com.taoym.voucher.common.response.OrderSyncResp;
import com.taoym.voucher.common.utils.HttpClientUtils;
import com.taoym.voucher.job.domain.XcxActivityOrder;
import com.taoym.voucher.job.domain.XcxUserInfo;
import com.taoym.voucher.job.mapper.XcxActivityOrderMapper;
import com.taoym.voucher.job.mapper.XcxUserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @coder taoym
 * @datetime 2021/6/27 17:39
 * @desc
 */
@Slf4j
@DisallowConcurrentExecution
public class ActivityOrderJob extends QuartzJobBean {

    @Resource
    private XcxActivityOrderMapper xcxActivityOrderMapper;
    @Value("${jutuike.order}")
    private String url;
    @Resource
    private XcxUserInfoMapper xcxUserInfoMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();

        // 下单者佣金率 = 可分配佣金率*队员佣金率
        BigDecimal distRate = new BigDecimal(jobDataMap.get("distRate").toString());
        BigDecimal teamRate = new BigDecimal(jobDataMap.get("teamRate").toString());
        BigDecimal orderUserRate = distRate.multiply(teamRate).setScale(3, BigDecimal.ROUND_DOWN);

        // 邀请人佣金=可分配佣金率*(1-下单者佣金率)
        BigDecimal chiefRate = distRate.multiply(new BigDecimal("1")
                .subtract(teamRate)).setScale(3, BigDecimal.ROUND_DOWN);

        Map<String, Object> param = new HashMap<>();
        param.put("apikey", jobDataMap.get("apiKey"));
        param.put("start_time", LocalDateTime.now().plusMinutes(-15));
        param.put("end_time", LocalDateTime.now());
        param.put("query_type", 2);
        param.put("page", 1);
        param.put("pageSize", 100);
        log.info("参数 {}", param);
        String resp = HttpClientUtils.doPost(url, JSON.toJSONString(param));
        log.info("订单同步数据 {}", resp);
        OrderSyncResp orderSyncResp = JSON.parseObject(resp, OrderSyncResp.class);

        if (!ObjectUtils.isEmpty(orderSyncResp) &&
                orderSyncResp.getCode().equals(1) &&
                !ObjectUtils.isEmpty(orderSyncResp.getData()) &&
                !ObjectUtils.isEmpty(orderSyncResp.getData().getData())) {
            // 构造入库参数
            List<XcxActivityOrder> xcxActivityOrders = new ArrayList<>(orderSyncResp.getData().getData().size());

            for (OrderSyncResp.Order order : orderSyncResp.getData().getData()) {
                XcxUserInfo xcxUserInfo = xcxUserInfoMapper.selectOne(new QueryWrapper<XcxUserInfo>()
                        .select("chief_uid")
                        .eq("uid", order.getSid()));

                XcxActivityOrder xcxActivityOrder = new XcxActivityOrder();
                xcxActivityOrder.setOrderSn(order.getOrderSn());
                xcxActivityOrder.setOrderPrice(order.getOrderPrice());
                xcxActivityOrder.setOrderTitle(order.getOrderTitle());
                xcxActivityOrder.setActId(order.getActId());
                xcxActivityOrder.setActName(order.getActName());
                xcxActivityOrder.setCreateTime(order.getCreateTime());
                xcxActivityOrder.setPayTime(order.getPayTime());
                xcxActivityOrder.setAllFee(order.getJtk_share_fee());
                xcxActivityOrder.setAllRate(order.getJtk_share_rate());
                xcxActivityOrder.setOrderUserUid(order.getSid());
                xcxActivityOrder.setChiefUid(ObjectUtils.isEmpty(xcxUserInfo) ? "000000" : xcxUserInfo.getChiefUid());
                xcxActivityOrder.setPayPrice(order.getPayPrice());
                xcxActivityOrder.setModifiedTime(order.getModifiedTime());
                xcxActivityOrder.setStatus(order.getStatus());
                xcxActivityOrder.setStatusDesc(order.getStatus_desc());
                // 实际佣金
                log.info("数据 {}", order);
                BigDecimal realFee = new BigDecimal(order.getJtk_share_fee())
                        .multiply(new BigDecimal(ActInfoEnum.getInstance(order.getActId()).getRate()))
                        .setScale(3, BigDecimal.ROUND_DOWN);
                xcxActivityOrder.setRealFee(realFee.toString());
                // 实际佣金率
                xcxActivityOrder.setRealRate(new BigDecimal(order.getJtk_share_rate())
                        .multiply(new BigDecimal(ActInfoEnum.getInstance(order.getActId()).getRate()))
                        .setScale(3, BigDecimal.ROUND_DOWN).toString());
                // 下单人佣金率和佣金
                xcxActivityOrder.setOrderUserRate(orderUserRate.toString());
                xcxActivityOrder.setOrderUserFee(realFee.multiply(orderUserRate)
                        .setScale(3, BigDecimal.ROUND_DOWN).toString());
                // 邀请人佣金率和佣金
                xcxActivityOrder.setChiefRate(chiefRate.toString());
                xcxActivityOrder.setChiefFee(realFee.multiply(chiefRate).setScale(3, BigDecimal.ROUND_DOWN).toString());

                xcxActivityOrder.setOrderPrice(order.getOrderPrice());

                xcxActivityOrders.add(xcxActivityOrder);
            }

            if (!CollectionUtils.isEmpty(xcxActivityOrders)) {
                log.info("插入到数据库的订单信息 {}", xcxActivityOrders);
                xcxActivityOrderMapper.insertOrUpdateList(xcxActivityOrders);
            }
        }
    }
}
